package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //上传文件
        String endPoint = "http://47.946.115:9000";
        String bucketName = "lease";
        String username = "minioadmin";
        String password = "minioadmin";
//登录
        MinioClient minioClient = MinioClient.builder().endpoint(endPoint).credentials(username, password).build();
        //判断是否有桶
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        //没有桶创建并设置访问权限
        if (!bucketExists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            String config="""
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(config).build());
        }

        //上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(file.getOriginalFilename()).stream(file.getInputStream(), file.getSize(), -1).build());

        //拼接回显地址
        String url = String.join("/",endPoint,bucketName,file.getOriginalFilename());
        return url;
    }

    public static void main(String[] args) {
        System.out.println("File.separator =" + File.separator);
    }
  }

